﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MockBusiness;
using MockDataTransferObject;
using MockCommon;
using System.Globalization;

namespace Presentation.AdminPresentation
{
    public partial class ListConsultant : System.Web.UI.Page
    {
        private ConsultantBusiness _consultantBusiness;
        private UserBusiness _userBusiness;
        private Label _warningLabel;
        private Label _errorLabel;
        private Label _successLabel;
        private CheckBox _allSearchCheckBox;
        private TextBox _nameTextBox;
        private DropDownList _typeDropDownList;
        private DropDownList _statusDropDownList;
        private Button _filterButton;
        private ListView _consultantListView;

        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                _consultantBusiness = ConsultantBusiness.RetrieveInstance();
                _userBusiness = UserBusiness.RetrieveInstance();
                _warningLabel = (Label)Master.FindControl("WarningLabel");
                _errorLabel = (Label)Master.FindControl("ErrorLabel");
                _successLabel = (Label)Master.FindControl("SuccessLabel");
                _allSearchCheckBox = (CheckBox)ListConsultantUserControl.FindControl("AllSearchCheckBox");
                _nameTextBox = (TextBox)ListConsultantUserControl.FindControl("NameTextBox");
                _typeDropDownList = (DropDownList)ListConsultantUserControl.FindControl("TypeDropDownList");
                _statusDropDownList = (DropDownList)ListConsultantUserControl.FindControl("StatusDropDownList");
                _filterButton = (Button)ListConsultantUserControl.FindControl("FilterButton");
                _consultantListView = (ListView)ListConsultantUserControl.FindControl("ConsultantListView");
                _filterButton.Click += new EventHandler(FilterButton_Click);
                _consultantListView.ItemDeleting += new EventHandler<ListViewDeleteEventArgs>(ConsultantListView_ItemDeleting);
                _consultantListView.ItemEditing += new EventHandler<ListViewEditEventArgs>(ConsultantListView_ItemEditing);
                _consultantListView.ItemCommand += new EventHandler<ListViewCommandEventArgs>(ConsultantListView_ItemCommand);
                _statusDropDownList.SelectedIndexChanged += new EventHandler(StatusDropDownList_SelectedIndexChanged);
                _allSearchCheckBox.CheckedChanged += new EventHandler(AllSearchCheckBox_CheckedChanged);
            }
            catch (MockException exception)
            {
                Application["error"] = exception;
                Response.Redirect("../Error.aspx");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["User"] != null)
            {
                User user = (User)Session["User"];
                if (user.Role.RoleName != "Admin")
                {
                    Server.Transfer("../NotAuthorized.aspx");
                }
            }
            else
            {
                Response.Redirect("../LogOn.aspx");
            }
            if (!Page.IsPostBack)
            {
                Loading();
            }
            else
            {
                _warningLabel.Text = "";
                _errorLabel.Text = "";
                _successLabel.Text = "";
            }
        }

        protected void ConsultantListView_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            try
            {
                _successLabel.Text = "";
                Label consultantIdLabel = _consultantListView.Items[e.ItemIndex].FindControl("ConsultantId") as Label;
                string consultantId = consultantIdLabel.Text;
                _consultantBusiness.Delete(consultantId);

                Label userIdLabel = _consultantListView.Items[e.ItemIndex].FindControl("UserId") as Label;
                string userId = userIdLabel.Text;
                _userBusiness.Delete(userId);

                _successLabel.Text = "Delete successfully";
                Loading();
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        protected void ConsultantListView_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            try
            {
                Label consultantIdLabel = _consultantListView.Items[e.NewEditIndex].FindControl("ConsultantId") as Label;
                string consultantId = consultantIdLabel.Text;
                Consultant consultant = _consultantBusiness.GetById(Guid.Parse(consultantId));
                string url = String.Format(CultureInfo.CurrentCulture, "UserProfile.aspx?uname={0}&rname={1}", consultant.User.UserName, consultant.User.Role.RoleName);
                Response.Redirect(url);
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        protected void StatusDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int value = Int32.Parse(_statusDropDownList.SelectedValue, CultureInfo.CurrentCulture);
                if (value == 0)
                {
                    _consultantListView.DataSource = _consultantBusiness.GetConsultantsByFilter("", "", "", "", true);
                }
                else if (value == 1)
                {
                    _consultantListView.DataSource = _consultantBusiness.GetConsultantsByFilter("", "", "", "", false);
                }
                _consultantListView.DataBind();
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        protected void ConsultantListView_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            try
            {
                 _successLabel.Text = "";
                 if (e.CommandName.ToUpper(CultureInfo.CurrentCulture) == "ACTIVE" || e.CommandName.ToUpper(CultureInfo.CurrentCulture) == "BLOCK")
                 {
                     int index = e.Item.DataItemIndex;
                     Label labelConsultantId = _consultantListView.Items[index].FindControl("ConsultantId") as Label;
                     Consultant consultant = _consultantBusiness.GetById(Guid.Parse(labelConsultantId.Text));
                     if (e.CommandName == "active")
                     {
                         consultant.User.IsActive = true;
                         _consultantBusiness.Update(consultant);
                     }
                     else if (e.CommandName == "block")
                     {
                         consultant.User.IsActive = false;
                         _consultantBusiness.Update(consultant);
                     }
                     _successLabel.Text = "Update successfully";
                     Loading();
                 }
            }
            catch (NullReferenceException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        protected void AllSearchCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (_allSearchCheckBox.Checked)
            {
                _statusDropDownList.AutoPostBack = false;
            }
            else
            {
                _statusDropDownList.AutoPostBack = true;
            }
        }

        protected void FilterButton_Click(object sender, EventArgs e)
        {
            try
            {
                string keyword = _nameTextBox.Text;
                int statusId = Int32.Parse(_statusDropDownList.SelectedValue, CultureInfo.CurrentCulture);
                int nameType = Int32.Parse(_typeDropDownList.SelectedValue, CultureInfo.CurrentCulture);
                bool isActive = statusId == 1 ? true : false;
                object source = null;
                if (nameType == 0)
                {
                    source = _consultantBusiness.GetConsultantsByFilter(keyword, "", "", "", isActive);
                }
                else if (nameType == 1)
                {
                    source = _consultantBusiness.GetConsultantsByFilter("", "", keyword, "", isActive);
                }
                else if (nameType == 2)
                {
                    source = _consultantBusiness.GetConsultantsByFilter("", "", "", keyword, isActive);
                }
                else if (nameType == 3)
                {
                    source = _consultantBusiness.GetConsultantsByFilter("", keyword, "", "", isActive);
                }
                _consultantListView.DataSource = source;
                _consultantListView.DataBind();
            }
            catch (ArgumentException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (FormatException exception)
            {
                _errorLabel.Text = exception.Message;
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }

        private void Loading()
        {
            try
            {
                _consultantListView.DataSource = _consultantBusiness.RetrieveAllConsultants();
                _consultantListView.DataBind();
            }
            catch (MockException exception)
            {
                _errorLabel.Text = exception.ExceptionMessage;
            }
        }
    }
}